/* eslint no-console: 0 */
/* global axios */
import ApiClient from '../ApiClient'

export const buildCreatePayload = ({
  message,
  isPrivate,
  contentAttributes,
  echoId,
  files,
  ccEmails = '',
  bccEmails = '',
  templateParams,
}) => {
  let payload
  if (files && files.length !== 0) {
    payload = new FormData()
    if (message) {
      payload.append('content', message)
    }
    files.forEach(file => {
      payload.append('attachments[]', file)
    })
    payload.append('private', isPrivate)
    payload.append('echoId', echoId)
    payload.append('ccEmails', ccEmails)
    payload.append('bccEmails', bccEmails)
  } else {
    payload = {
      content: message,
      private: isPrivate,
      echoId: echoId,
      contentAttributes: contentAttributes,
      ccEmails: ccEmails,
      bccEails: bccEmails,
      templateParams: templateParams,
    }
  }
  return payload
}

export const buildCreatePayloadUseForm = ({
  message,
  isPrivate,
  contentAttributes,
  echoId,
  files,
  ccEmails = '',
  bccEmails = '',
  templateParams,
}) => {
  const payload = new FormData()
  if (message) {
    payload.append('content', message)
  }
  if (files && files.length !== 0) {
    files.forEach(file => {
      payload.append('attachments[]', file)
    })
  }
  payload.append('private', isPrivate)
  payload.append('echoId', echoId)
  payload.append('ccEmails', ccEmails)
  payload.append('bccEmails', bccEmails)
  payload.append('templateParams', templateParams)

  return payload
}

class MessageApi extends ApiClient {
  constructor () {
    super('conversations', { accountScoped: true })
  }

  create ({
    conversationId,
    message,
    private: isPrivate,
    contentAttributes,
    echoId: echoId,
    files,
    ccEmails = '',
    bccEmails = '',
    templateParams,
  }) {
    return axios({
      method: 'post',
      url: `${this.url}/${conversationId}/messages`,
      data: buildCreatePayloadUseForm({
        message,
        isPrivate,
        contentAttributes,
        echoId,
        files,
        ccEmails,
        bccEmails,
        templateParams,
      }),
    })
  }

  delete (conversationID, messageId) {
    return axios.delete(`${this.url}/${conversationID}/messages/${messageId}`)
  }

  getPreviousMessages ({ conversationId, before }) {
    return axios.get(`${this.url}/${conversationId}/messages`, {
      params: { before },
    })
  }
}

export default new MessageApi()
